package com.z.controller;

import com.z.pojo.Cart;
import com.z.pojo.Order;
import com.z.pojo.Users;
import com.z.service.OrderService;
import com.z.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet("/addOrder")
public class AddOrderServlet extends HttpServlet {
    private OrderService orderService = new OrderServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Users user = null;
        user = (Users) req.getSession().getAttribute("users");

        if(user == null){
            String referer = req.getHeader("referer");
            req.getSession().setAttribute("referer",referer);
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
        } else {
            //正常添加订单操作
            String gids = req.getParameter("pids");
            String sprice = req.getParameter("sprice");
            String gnum = req.getParameter("gnum");
            String[] ps = gids.split(",");

            String[] sp = sprice.split(",");

            String[] gn = gnum.split(",");

            for (String p : ps) {
                System.out.println(p);
            }

            Map<Integer, Cart> carts = (Map<Integer, Cart>)req.getSession().getAttribute("carts");

            Order order = new Order();

            List<Cart> gidss = new ArrayList<>();

            for (int i = 0; i < ps.length; i++) {

                order.setOid(UUID.randomUUID().toString());
                order.setOtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                order.setState("未确认");
                order.setUid(user.getUid());
                order.setGid(Integer.valueOf(ps[i]));
                order.setSprice(Double.valueOf(sp[i]));
                order.setGnum(Integer.valueOf(gn[i]));
            }

            try {
                orderService.addOrder(order);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            req.setAttribute("param",order.getOid());
            resp.sendRedirect(req.getContextPath()+"/order2.jsp?oid="+order.getOid());
        }

    }
}